import HTTP from "../util/http"
export class ClassicModel extends HTTP{
    getLatest() {
        return new Promise((resolve, reject) => {
            this.request({
                url: 'classic/latest',
                //url: 'latest',
                success: (res) => {
                    resolve(res);
                    this._setLatestIndex(res.index);
                    let key = this._getKey(res.index);
                    wx.setStorageSync(key, res);
                }
            })
        })
    }
    getClassic(index, nextOrPrevious) {
        // 缓存中寻找 or API 写入到缓存中
        // key 确定key
        let key = nextOrPrevious === 'next' ? this._getKey(index + 1) : this._getKey(index - 1);
        let classic = wx.getStorageSync(key);
        if (!classic) {
            return new Promise((resolve, reject) => {
                this.request({
                    url: `classic/${index}/${nextOrPrevious}`,
                    success: (res)=>{
                        wx.setStorageSync(this._getKey(res.index), res);
                        resolve(res)
                    }
                })
            })
        } else {
            return Promise.resolve(classic);
        }
    }


    isFirst(index) {
        return index === 1;
    }

    isLatest(index) {
        let latestIndex = this._getLatestIndex();
        return index === latestIndex;
    }

    _setLatestIndex(index) {
        wx.setStorageSync('latest', index);
    }

    _getLatestIndex() {
        let index = wx.getStorageSync('latest');
        return index;
    }

    _getKey(index) {
        let key = `classic-${index}`;
        return key;
    }
}